package com.pingan.haofang.searchcloud.monitor.dao;

import java.util.List;

import javax.persistence.EntityManager;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

import com.pingan.haofang.searchcloud.monitor.convert.ColumnToBean;
import com.pingan.haofang.searchcloud.monitor.domain.DashboardWarningHistory;
import com.pingan.haofang.searchcloud.monitor.dto.WarningHistoryCountDTO;

@Repository
public interface DashboardWarningHistoryDao
        extends JpaRepository<DashboardWarningHistory, Long>, JpaSpecificationExecutor<DashboardWarningHistory> {

    default List<WarningHistoryCountDTO> countByConfigId(List<Long> configIds, EntityManager entityManager) {
        StringBuilder sqlBuilder = new StringBuilder("select config_id as configId,max(create_time) as date"
                + " from t_dashboard_warning_history where 1=1 ");

        if (CollectionUtils.isNotEmpty(configIds)) {
            String configIdJoin = StringUtils.join(configIds, ",");
            sqlBuilder.append(" and config_id in (" + configIdJoin + ")");
        }

        sqlBuilder.append(" group by config_id");

        javax.persistence.Query query = entityManager.createNativeQuery(sqlBuilder.toString());

        List<WarningHistoryCountDTO> datas = query.unwrap(SQLQuery.class)
                .setResultTransformer(new ColumnToBean(WarningHistoryCountDTO.class)).list();
        return datas;
    }
}